<?php

namespace app\uniapp\controller;

use app\common\exception\MiException;
use app\common\service\CommonSiteConfigService;
use app\model\site\UserPointsLog;
use app\Request;
use app\service\wx\WxMpService;
use app\uniapp\service\CouponService;
use app\uniapp\service\SmsService;
use app\uniapp\service\UniAuthService;
use app\uniapp\service\UserCouponService;
use app\uniapp\service\UserService;
use Exception;
use thans\jwt\facade\JWTAuth;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;
use think\response\Json;

class LoginController extends UniController
{

    protected array $middleware = [];

    /**
     * 微信小程序登录
     * @return Json
     * @throws Exception
     */
    public function loginWxMp(Request $request): Json
    {
        $code = $request->post('code');
        $post = $request->post();
        $platform = getUniPlatform();
        $loginConfig = CommonSiteConfigService::instance()->getConfigValue(UniAuthService::instance()->getSiteId(), CommonSiteConfigService::LOGIN);
        $config = CommonSiteConfigService::instance()->getConfigValue(UniAuthService::instance()->getSiteId(), CommonSiteConfigService::WX_MP);
        $session = WxMpService::instance($config)->getWxMpSession($code);
        // 判断openid是否存在
        $userId = UserService::instance()->getUserIdByOauthId($session['openid'], $platform);
        // 查询用户信息
        $user = $userId ? UserService::instance()->setPkWhere($userId)->find() : null;

        if ($user){ // 用户已存在，直接登录
            $user = UserService::instance()->updateLoginUser($user, $post);
        }else{  // 用户不存在，注册并登录
            $userData = [
                'site_id' => UniAuthService::instance()->getSiteId(),
                'nickname' => getNickname(),
//                'avatar' =>  UserService::instance()->downLoadWxAvatar($post['avatar']),
                'avatar' =>  getAvatar(),
                'mobile' => $post['mobile']??'',
                'register_type' => 'wxmp',
                'parent_id' => $post['parent_id']??0,
            ];
            $oauth = [
                'oauth_id' => $session['openid'],
                'oauth_type' => $platform,
                'unionid' => $session['unionid']??'',
                'site_id' => UniAuthService::instance()->getSiteId(),
            ];

            $user = UserService::instance()->createLoginUser($userData, $oauth);
        }
        // 生成token
        $tokenUser = [
            'id'  => $user->id,
            'name'  => $user->nickname,
        ];
        $token = JWTAuth::builder($tokenUser);

        // 返回token
        return jsonSuccess([
            'token' => $token,
        ]);

    }

    /**
     * 手机号密码登录
     *
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws MiException
     * @throws Exception
     */
    public function localLogin(){
        $loginType = $this->post('loginType');
        $mobile = $this->post('mobile');
        $password = $this->post('password');
        $code = $this->post('code');
        $user = null;

        if($loginType == 'password'){
            $user = UserService::instance()->setWhere([
                ['mobile', '=', $mobile],
                ['password', '=', md5($password)]
            ])->find();
            if (!$user) return jsonError("手机号或密码错误");
        }elseif ($loginType == 'sms') {  //
            // todo: 短信验证码登录，这里允许注册
            // 验证短信验证码
            if (SmsService::instance()->validateCode($code, $mobile)){

                //  短信验证码验证通过，登录或者注册
                $user = UserService::instance()->setWhere([
                    ['mobile', '=', $mobile],
                ])->find();
                if (!$user) { // 注册
                    $user = UserService::instance()->createLoginUser([
                        'site_id' => UniAuthService::instance()->getSiteId(),
                        'mobile' => $mobile,
                        'nickname' => UserService::instance()->makeNickname(),
                        'avatar' => UserService::instance()->makeAvatar(),
                        'register_type' => 'mobile'
                    ]);
                }

            }else{
                return jsonError("短信验证码错误");
            }

        }


        // 生成token
        $token = uuid();
        // 保存token到缓存
        UniAuthService::instance()->setLoginToken($token, $user->id);

        return jsonSuccess([
            'token' => $token,
        ]);


    }


    /**
     * 获取微信小程序手机号
     * @throws MiException
     * @throws Exception
     */
    public function getPhoneWxMp(Request $request): Json
    {
        $code = $request->post('code');
        if (!$code) return jsonError(PARAM_ERROR);
        $config = CommonSiteConfigService::instance()->getConfigValue(UniAuthService::instance()->getSiteId(), CommonSiteConfigService::WX_MP);
        $wxmpSer = WxMpService::instance($config);
        $accessToken = $wxmpSer->getAccessToken();
        $phoneInfo = $wxmpSer->getPhone($code, $accessToken);
        return jsonSuccess([
            'mobile' => $phoneInfo['phoneNumber']
        ]);
    }


    /**
     * 检查用户是否已经注册
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function checkRegister(Request $request): Json
    {
        $code = $request->post('code');
        $isRegister = UserService::instance()->checkRegisterByPlatForm($code);

        return jsonSuccess([
            'isRegister' => $isRegister,
        ]);
    }
}
